/* eslint-disable react/self-closing-comp */
import React, { useEffect } from 'react';
import classnames from 'classnames';
import QueueAnim from 'rc-queue-anim';
import './index.less';

interface PopupProps {
  visible: boolean;
  dismissText?: string;
  okText?: string;
  title?: string;
  onOk?: () => boolean | undefined;
  onDismiss?: () => void;
  onClose?: () => void;
  className?: string;
}

const Index: React.FC<PopupProps> = ({
  visible,
  children,
  title,
  dismissText,
  okText,
  onOk,
  onClose,
  onDismiss,
  className,
}) => {
  useEffect(() => {
    if (visible) {
      document.body.style.setProperty('overflow-y', 'hidden');
    } else {
      document.body.style.removeProperty('overflow-y');
    }
    return () => {
      document.body.style.removeProperty('overflow-y');
    };
  }, [visible]);
  const handleClose = () => {
    if (typeof onClose === 'function') {
      onClose();
    }
  };
  const handleOk = () => {
    if (typeof onOk === 'function') {
      if (onOk() === false) {
        return;
      }
    }
    handleClose();
  };
  const handleDismiss = () => {
    if (typeof onDismiss === 'function') {
      onDismiss();
    }
    handleClose();
  };

  return (
    <div className={classnames('hr-popup', className)}>
      {visible && <div className="hr-popup-mask" onClick={handleClose}></div>}
      <QueueAnim animConfig={[{ translateY: [0, 1] }, { translateY: [0, '100%'] }]}>
        {visible && (
          <div className="hr-popup-main" key="hr-popup-main">
            <div className="hr-popup-header">
              <div className="hr-popup-item hr-popup-header-left" onClick={handleDismiss}>
                {dismissText}
              </div>
              <div className="hr-popup-item hr-popup-title">{title}</div>
              <div className="hr-popup-item hr-popup-header-right" onClick={handleOk}>
                {okText}
              </div>
            </div>
            <div className="hr-popup-body">{children}</div>
          </div>
        )}
      </QueueAnim>
    </div>
  );
};
Index.defaultProps = {
  dismissText: '取消',
  okText: '确定',
};
export default Index;
